#ifdef _MSC_VER
/*
 * we do not want the warnings about the old deprecated and unsecure CRT functions
 * since these examples can be compiled under *nix as well
 */
#define _CRT_SECURE_NO_WARNINGS
#endif

#include <pcap.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <iostream>
#include <list>
#include <map>

#define VIDEO 1
#define BROWSING 2
#define DOWNLOAD 3
#define NON_CLASSIFIED 0

using namespace std;

class Sessions {

public:

    struct TcpKey {
        u_char srcIP[4];
        u_char dstIP[4];

        int srcPort;
        int dstPort;

        u_char protocol;

		string link;
		int sessType;
    };

    struct TcpPacket {
        u_char* payload;
        unsigned seqNumber;
        int packetLen;
    };

	map<string, int> SessionTypesByHost;
	map<string, int> SessionTypesByContent;

    map<TcpKey, list<TcpPacket> > AllSessions;

    bool AddPacket(const u_char* packet, u_char compIp[], bool searchHttp);

    bool DumpSession(u_char* defIp, int packetNum, char* resFileName);

    bool DumpReverseSession(u_char* defIp, char* resFileName);

private:
	bool PrintType(int type);

	bool FindHttp(list<TcpPacket> listToSearch);

	bool PrintMonitor(map<TcpKey, list<TcpPacket> >::iterator itPrint, TcpPacket tempPacket);

	bool UpdateMapKey(map<TcpKey, list<TcpPacket> >::iterator itPrint, int sessType);

	int FindHttpHostName(TcpPacket tempPacket);

	int FindHttpContentType(TcpPacket tempPacket);

	bool DefineMap();

	bool TcpKeyCompare(TcpKey firstKey, TcpKey secondKey);

    bool IpCompare(u_char neededIP[4], const u_char currentIP[4]);

    int WriteList(string resFile, list<TcpPacket> listToWrite);
};


inline bool operator < (const Sessions::TcpKey &l, const Sessions::TcpKey &r) { return l.srcIP < r.srcIP; }
inline bool operator < (const Sessions::TcpPacket &l, const Sessions::TcpPacket &r) { return l.seqNumber < r.seqNumber; }
